<!-- RTC 11-15 -->
<template>
  <el-row>
        <el-col :span="8">
          <el-card style="width: 100%; min-height: 300px; color: #333">
            <div style="padding-bottom: 10px; border-bottom: 1px solid #ccc">在线用户<span style="font-size: 12px">（点击聊天气泡开始聊天）</span></div>
            <div style="padding: 10px 0" v-for="user in users" :key="user.username">
              <span>{{ user.username }}</span>
              <i class="el-icon-chat-dot-round" style="margin-left: 10px; font-size: 16px; cursor: pointer"
                @click="toVideoChat(user)"></i>
              <span style="font-size: 12px;color: limegreen; margin-left: 5px" v-if="user.username === chatUser">chatting...</span>
            </div>
          </el-card>
        </el-col>
        <el-col :span="16" v-if="videoProps.visible">
          <div class="default-container">
            <VideoComponent 
            @exit="exit"
            :receiveOppositeUserId="videoProps.oppositeUserId" 
            :receiveRoomId="videoProps.roomId" 
            :receiveUserId="videoProps.userId" 
            :receiveVideoType="videoProps.videoType" 
            :videoVisible="videoProps.visible"></VideoComponent>
          </div>
        </el-col>
        <el-col :span="16" v-else>
          <div class="default-container no-container"></div>
        </el-col>
      </el-row>
</template>
<script>
import VideoComponent from '@/components/VideoComponent.vue'
let socket;

export default {
  data() {
    return {
      user: {},
      users: [],
      chatUser:"",
      videoProps:{
        oppositeUserId:"",
        roomId:"",
        userId:"",
        videoType:"",
        visible: false
      }
    };
  },
  components:{
    VideoComponent
  },
  created() {
    // let urls = window.location.search.split("?")[1].split("&");
    
  },
  watch:{

  },

  mounted() {
    this.init()
    console.log(this.$route.query)
    if(this.$route.query.from){
      this.videoProps = {
        oppositeUserId: this.$route.query.from,
        userId: this.user.username,
        roomId: this.computeRoomId(this.$route.query.from, this.user.username),
        videoType: "2",
        visible: true
      }
    }
  },
  beforeDestroy(){

  },
  methods: {
    exit(){
      console.log('触发了')
      this.resetVideoProps()
      this.sendVideo('[结束通话]')
      this.chatUser = ""
    },
    resetVideoProps(){
      this.videoProps = {
        oppositeUserId:"",
        roomId:"",
        userId:"",
        videoType:"",
        visible: false
      }
    },
    toVideoChat(user){
      this.chatUser = user.username
      this.videoProps = {
        oppositeUserId: user.username,
        userId: this.user.username,
        roomId: this.computeRoomId(user.username, this.user.username),
        videoType: "1",
        visible: true
      }
      this.sendVideo('[视频通话]')
    },
    computeRoomId(id1, id2){
      return id1 > id2?`${id2}_${id1}`:`${id1}_${id2}`
    },
    sendVideo(msg) {
      if (!this.chatUser) {
        this.$message({type: 'warning', message: "请选择聊天对象"})
        return;
      }
      if (typeof (WebSocket) == "undefined") {
        console.log("您的浏览器不支持WebSocket");
      } else {
        console.log("您的浏览器支持WebSocket");
        // 组装待发送的消息 json
        // {"from": "zhang", "to": "admin", "text": "聊天文本"}
        let message = {from: this.user.username, to: this.chatUser, text: msg}
        console.log(message)
        socket.send(JSON.stringify(message));  // 将组装好的json发送给服务端，由服务端进行转发
        // 构建消息内容，本人消
      }
    },
    init() {
      this.user = localStorage.getItem("user") ? JSON.parse(localStorage.getItem("user")) : {}
      let username = this.user.username;
      let _this = this;
      if (typeof (WebSocket) == "undefined") {
        console.log("您的浏览器不支持WebSocket");
      } else {
        console.log("您的浏览器支持WebSocket");
        let socketUrl = "ws://localhost:9090/imserver/" + username;
        if (socket != null) {
          socket.close();
          socket = null;
        }
        // 开启一个websocket服务
        socket = new WebSocket(socketUrl);
        //打开事件
        socket.onopen = function () {
          console.log("websocket已打开");
        };
        //  浏览器端收消息，获得从服务端发送过来的文本消息
        socket.onmessage = function (msg) {
          console.log("收到数据====" + msg.data)
          let data = JSON.parse(msg.data)  // 对收到的json数据进行解析， 类似这样的： {"users": [{"username": "zhang"},{ "username": "admin"}]}
          if (data.users) {  // 获取在线人员信息(格式满足{"users": [{"username": "zhang"}这样的就是在线人员
            _this.users = data.users.filter(user => user.username !== username)  // 获取当前连接的所有用户信息，并且排除自身，自己不会出现在自己的聊天列表里
          } else {
            // 如果服务器端发送过来的json数据 不包含 users 这个key，那么发送过来的就是聊天文本json数据
            //  // {"from": "zhang", "text": "hello"}，这样就不是在线人员 就是发送的消息信息
            // if (data.from === _this.chatUser) {
              // _this.messages.push(data) // message就是一个数组，用于存储目前的聊天记录
              // 构建消息内容
              // _this.createContent(data.from, null, data.text)
            // }
            console.log(data)
            _this.chatUser = data.from
            if (data.text == '[视频通话]'){
              _this.videoProps = {
                oppositeUserId: data.from,
                userId: _this.user.username,
                roomId: _this.computeRoomId(data.from, _this.user.username),
                videoType: "2",
                visible: true
              }
            } else if(data.text == '[结束通话]'){
              _this.resetVideoProps()
              _this.chatUser = ""
            }
          }
        };
        //关闭事件
        socket.onclose = function () {
          console.log("websocket已关闭");
        };
        //发生了错误事件
        socket.onerror = function () {
          console.log("websocket发生了错误");
        }
      }
    }
  }
}
</script>

<style scoped>
.video-chat {
  width: 96%;
  height: 90%;
  padding: 10px;
}
.default-container{
  width: 90%;
  height: 300px;
}
.no-container{
  background-color: #e1e1e1;
}
</style>